<?php
class controller_MessageController {
    private $view;
    private $args;

    public function setView(View $view) {
        $this->view = $view;
        return $this;
    }

    public function setArgs($args = null) {
        if(null != $args) {
            $this->args = $args;
        }
        return $this;
    }

    public function run() {
        $user = model_UserMapper::getCurrentUser();
        if (null == $user->getId()) {
            $this->view->message = 'У вас нет доступа к этой функции!';
            $this->view->setRenderTemplate("error.phtml");
            return;
        } else {
            if(empty($this->args['action'])) {
                $this->index();
            } else {
                switch ($this->args['action']) {

                    case 'income':
                        $this->index();
                        break;

                    case 'send':
                        $this->index();
                        break;

                    case 'edit':
                        $this->edit();
                        break;

                    case 'delete':
                        $this->delete();
                        break;

                    case 'save':
                        $this->save();
                        break;

                    default:
                        $this->index();
                }
            }
        }
    }

    public function index() {
        $mapper = new model_MessageMapper();
        $user = model_UserMapper::getCurrentUser();

        if(empty($this->args['id'])) { //если id пустой, то отрисовывем все новости (fetchAll)

            $nums = 8; // количество постов на страницу

             if (empty($this->args['action']) || 'income' == $this->args['action']) {
                $pages = model_ConfigMapper::getPages($nums, $mapper->getTable(), $user->getId(), 'komu');
            } else {
                $pages = model_ConfigMapper::getPages($nums, $mapper->getTable(), $user->getId(), 'kto');
            }
            
            if (!empty($this->args['page'])) {
                if (1 > $this->args['page']) {
                    $page = 1;
                } elseif($this->args['page']>$pages) {
                    $page = $pages;
                } else {
                    $page = $this->args['page'];
                }
            } else {
                $page = 1;
            }

            $start = ($page - 1)* $nums;

            if (empty($this->args['action']) || 'income' == $this->args['action']) {
                $this->view->state = 'income';
                $this->view->allModels = $mapper->fetchAll($user->getId(), 'komu', $start, $nums);
            } else {
                $this->view->state = 'send';
                $this->view->allModels = $mapper->fetchAll($user->getId(), 'kto', $start, $nums);
            }

            $link = 'controller=message&action='. $this->view->state;
            $this->view->paginator = model_ConfigMapper::getPaginator($page, $pages, $link);
            $this->view->setRenderTemplate("messages/indexFetchAll.phtml");

        } else { //если же он указан, то ищем новость с этим id
            $this->view->state = 'find';
            $this->view->oneModel = $mapper->find($this->args['id'], $user);

            if(null != $this->view->oneModel->getId()) {
                $this->view->setRenderTemplate("messages/indexFind.phtml");

            } else {
                $this->view->message = 'Такой новости нет!';
                $this->view->setRenderTemplate("error.phtml");
            }
        }
    }


    public function edit() {
        if(!empty($this->args['id'])){
            $this->view->selected = $this->args['id'];
        } else {
            $this->view->selected = 0;
        }
        $user = new model_UserMapper();
        $this->view->allUsers = $user->fetchAll();
        $this->view->setRenderTemplate("messages/edit.phtml");
    }


    public function delete() {
        $user = model_UserMapper::getCurrentUser();
        $mapper = new model_MessageMapper();
        $message = $mapper->find($this->args['id'], $user);

        if($user->getId() != $message->getKto() && $user->getId() != $message->getKomu()) {
            $this->view->message = 'У вас нет доступа к этому сообщению!';
            $this->view->link = '<a href="index.php?controller=message">К сообщениям</a>';
            $this->view->setRenderTemplate("error.phtml");
            return;
        }

        if(!empty($this->args['id'])) {
            $mapper->delete($this->args['id']);
        }

        $this->view->link = 'index.php?controller=message';
        $this->view->setRenderTemplate("redirect.phtml");
    }

    public function save() {

        if(!empty($_POST)) {

            $mapper = new model_MessageMapper();
            $post = model_ConfigMapper::validate($_POST);

            $this->view->message = $mapper->checkMsg($post);

            if (empty($this->view->message)) {

                $user = model_UserMapper::getCurrentUser(); // смотри метод
                $post['kto'] = $user->getId();
                $post['date'] = date('Y-m-d H:i:s');
                $post['isread'] = 0;

                $post['text'] = model_ConfigMapper::sqlValid($post['text']);

                $model = new model_MessageModel($post);

                $mapper->save($model);
// сделать переход на страничку - сообщение отравлено!
                $this->view->link = 'index.php?controller=message';
                $this->view->setRenderTemplate("redirect.phtml");
                return;
            } else {
                $user = new model_UserMapper();
                $this->view->allUsers = $user->fetchAll();
                $this->view->setRenderTemplate("messages/edit.phtml");
                return;
            }
        } else {
            $this->view->message = 'Ошибка запроса';
            $this->view->setRenderTemplate("error.phtml");
            return;
        }
    }
}